package com.springboot.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.demo.entity.po.SysCode;
import com.springboot.demo.entity.po.SysUser;
import com.springboot.demo.service.SysCodeService;
import com.springboot.demo.service.SysUserService;
import com.springboot.demo.service.impl.mapper.SysCodeMapper;
import com.springboot.demo.service.impl.mapper.SysUserMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * @Description：
 * @Date： Created in 2021/12/30
 * @author： jianbin.lei
 * @Auto： <a href="mailto:493168771@qq.com">jianbin.lei</a>
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class SysCodeServiceImpl extends ServiceImpl<SysCodeMapper, SysCode> implements SysCodeService {

    Logger logger = LogManager.getLogger(SysCodeServiceImpl.class.getName());

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public List<SysCode> getList() {
        System.out.println("CacheManager type : " + cacheManager.getClass());
        QueryWrapper<SysCode> queryWrapper = new QueryWrapper<SysCode>();
        queryWrapper.eq("DEL_FLAG",Boolean.FALSE);
        List<SysCode> sysCodes = this.baseMapper.selectList(queryWrapper);
        logger.info("1st:count:"+sysCodes.size());
        sysCodes = this.baseMapper.selectList(queryWrapper);
        logger.info("2st:count:"+sysCodes.size());
        StringBuilder sb= new StringBuilder("");
        for(SysCode ao:sysCodes){
            sb.setLength(0);
            sb.append("id:").append(ao.getId());
            this.redisTemplate.opsForValue().set(sb.toString(),ao);
        }
        return sysCodes;
    }

    @Override
    public SysCode getSysCodeByDictCode(Long id) {
        QueryWrapper<SysCode> queryWrapper = new QueryWrapper<SysCode>();
        queryWrapper.eq("DEL_FLAG",Boolean.FALSE);
        queryWrapper.eq("ID",id);
        String key = "id:"+id;
        SysCode rt = null;
        if(redisTemplate.opsForValue().get(key) != null){
            rt = (SysCode) redisTemplate.opsForValue().get(key);
            logger.info("result from redis");
        }else{
            rt = this.baseMapper.selectById(id);
            redisTemplate.opsForValue().set(key,rt);
            logger.info("result from db");
        }
        return rt;
    }
}
